package com.member.shop.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.utils.DateUtils;
import com.member.common.utils.fy.HttpUtil;
import com.member.common.utils.fy.SignatureUtils;
import com.member.shop.domain.SysBizShopCertification;
import com.member.shop.domain.SysBizUserAddress;
import com.member.shop.dto.UserAddressDelExpDto;
import com.member.shop.dto.UserAddressExpDto;
import com.member.shop.mapper.SysBizUserAddressMapper;
import com.member.shop.service.ISysBizShopCertificationService;
import com.member.shop.service.ISysBizUserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址Service业务层处理
 *
 * @author lixinchen
 * @date 2024-01-09
 */
@Service
@Slf4j
public class SysBizUserAddressServiceImpl extends ServiceImpl<SysBizUserAddressMapper, SysBizUserAddress> implements ISysBizUserAddressService {
    @Resource
    private SysBizUserAddressMapper sysBizUserAddressMapper;

    @Value("${mall.order.merchantUrl}")
    private String merchantUrl;

    @Value("${mall.order.deleteMerchantUrl}")
    private String deleteMerchantUrl;

    @Value("${mall.order.privateKey}")
    private String privateKey;

    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;

    /**
     * 查询地址
     *
     * @param id 地址主键
     * @return 地址
     */
    @Override
    public SysBizUserAddress selectSysBizUserAddressById(Long id) {
        return sysBizUserAddressMapper.selectById(id);
    }

    /**
     * 查询地址列表
     *
     * @param queryWrapper 地址
     * @return 地址
     */
    @Override
    public List<SysBizUserAddress> selectSysBizUserAddressList(LambdaQueryWrapper<SysBizUserAddress> queryWrapper) {
        return sysBizUserAddressMapper.selectList(queryWrapper);
    }

    /**
     * 新增地址
     *
     * @param sysBizUserAddress 地址
     * @return 结果
     */
    @Override
    public int insertSysBizUserAddress(SysBizUserAddress sysBizUserAddress) {
        sysBizUserAddress.setCreateTime(DateUtils.getNowDate());
        return sysBizUserAddressMapper.insert(sysBizUserAddress);
    }

    /**
     * 修改地址
     *
     * @param sysBizUserAddress 地址
     * @return 结果
     */
    @Override
    public int updateSysBizUserAddress(SysBizUserAddress sysBizUserAddress) {
        sysBizUserAddress.setUpdateTime(DateUtils.getNowDate());
        return sysBizUserAddressMapper.updateById(sysBizUserAddress);
    }

    /**
     * 批量删除地址
     *
     * @param ids 需要删除的地址主键
     * @return 结果
     */
    @Override
    public int deleteSysBizUserAddressByIds(Long[] ids) {
        return sysBizUserAddressMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除地址信息
     *
     * @param id 地址主键
     * @return 结果
     */
    @Override
    public int deleteSysBizUserAddressById(Long id) {
        return sysBizUserAddressMapper.deleteById(id);
    }

    @Override
    public void updateAddress(SysBizUserAddress sysBizUserAddress) {
        // 先判断是不是默认地址
        if (sysBizUserAddress.getStatus() == 1) {
            sysBizUserAddressMapper.update(SysBizUserAddress.builder().status(0).build(), new LambdaUpdateWrapper<SysBizUserAddress>()
                    .eq(SysBizUserAddress::getUserId, sysBizUserAddress.getUserId()));
        }
        sysBizUserAddressMapper.updateById(sysBizUserAddress);
    }

    @Override
    public void insertAddress(SysBizUserAddress sysBizUserAddress) {
        // 先判断是不是默认地址
        if (sysBizUserAddress.getStatus() == 1) {
            sysBizUserAddressMapper.update(SysBizUserAddress.builder().status(0).build(), new LambdaUpdateWrapper<SysBizUserAddress>()
                    .eq(SysBizUserAddress::getUserId, sysBizUserAddress.getUserId()));
        }
        sysBizUserAddressMapper.insert(sysBizUserAddress);
    }

    @Override
    public List<SysBizUserAddress> selectSysBizUserAddressList(SysBizUserAddress sysBizUserAddress) {
        return sysBizUserAddressMapper.selectSysBizUserAddressList(sysBizUserAddress);
    }

    @Override
    @Async
    public void removeErpAddress(Long id) {
        UserAddressDelExpDto userAddressDelExpDto = new UserAddressDelExpDto();
        userAddressDelExpDto.setAddressId(String.valueOf(id));
        // 时间戳
        String timeStamp = String.valueOf(System.currentTimeMillis());

        // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
        String sign = null;
        try {
            sign = SignatureUtils.signWithSHA1(JSON.toJSONString(userAddressDelExpDto), SignatureUtils.getPrivateKey(privateKey));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("timeStamp", timeStamp);
        requestBody.put("sign", sign);
        requestBody.put("data", JSON.toJSONString(userAddressDelExpDto));
        log.info("请求体:{}", JSON.toJSONString(userAddressDelExpDto));

        // 发送 POST 请求
        String response = HttpUtil.postJson(deleteMerchantUrl, JSON.toJSONString(requestBody));
        log.info("订单推送------------:{}", response);
        // 解析响应
        JSONObject jsonResponse = JSON.parseObject(response);
        int code = jsonResponse.getIntValue("code");
        log.info("返回值------------:{}", jsonResponse);
    }

    @Override
    @Async
    public void updateAddressErp(SysBizUserAddress sysBizUserAddress, Long userId) {
        UserAddressExpDto userAddressExpDto = new UserAddressExpDto();
        userAddressExpDto.setAddressId(String.valueOf(sysBizUserAddress.getId()));
        List<SysBizShopCertification> sysBizShopCertifications = sysBizShopCertificationService.selectSysBizShopCertificationList(
                new LambdaQueryWrapper<SysBizShopCertification>()
                        .eq(SysBizShopCertification::getUserId, userId)
                        .eq(SysBizShopCertification::getDeleted, 0)
        );
        if (!CollectionUtils.isEmpty(sysBizShopCertifications)) {
            userAddressExpDto.setName(sysBizShopCertifications.get(0).getShopName());
        } else {
            userAddressExpDto.setName("无");
        }
        userAddressExpDto.setAddress(sysBizUserAddress.getDetails());
        userAddressExpDto.setProvince(sysBizUserAddress.getProvince());
        userAddressExpDto.setCity(sysBizUserAddress.getCity());
        userAddressExpDto.setArea(sysBizUserAddress.getArea());
        userAddressExpDto.setStreet(sysBizUserAddress.getStreet());
        // 时间戳
        String timeStamp = String.valueOf(System.currentTimeMillis());

        // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
        String sign = null;
        try {
            sign = SignatureUtils.signWithSHA1(JSON.toJSONString(userAddressExpDto), SignatureUtils.getPrivateKey(privateKey));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("timeStamp", timeStamp);
        requestBody.put("sign", sign);
        requestBody.put("data", JSON.toJSONString(userAddressExpDto));
        log.info("请求体:{}", JSON.toJSONString(userAddressExpDto));

        // 发送 POST 请求
        String response = HttpUtil.postJson(merchantUrl, JSON.toJSONString(requestBody));
        log.info("订单推送------------:{}", response);
        // 解析响应
        JSONObject jsonResponse = JSON.parseObject(response);
        log.info("返回值------------:{}", jsonResponse);
        int code = jsonResponse.getIntValue("code");
    }

    @Override
    @Async
    public void insertAddressErp(SysBizUserAddress sysBizUserAddress, Long userId) {
        //对接erp
        UserAddressExpDto userAddressExpDto = new UserAddressExpDto();
        List<SysBizShopCertification> sysBizShopCertifications = sysBizShopCertificationService.selectSysBizShopCertificationList(
                new LambdaQueryWrapper<SysBizShopCertification>()
                        .eq(SysBizShopCertification::getUserId, userId)
                        .eq(SysBizShopCertification::getDeleted, 0)
        );
        if (!CollectionUtils.isEmpty(sysBizShopCertifications)) {
            userAddressExpDto.setName(sysBizShopCertifications.get(0).getShopName());
        } else {
            userAddressExpDto.setName("无");
        }
        userAddressExpDto.setAddressId(String.valueOf(sysBizUserAddress.getId()));
        userAddressExpDto.setAddress(sysBizUserAddress.getDetails());
        userAddressExpDto.setProvince(sysBizUserAddress.getProvince());
        userAddressExpDto.setCity(sysBizUserAddress.getCity());
        userAddressExpDto.setArea(sysBizUserAddress.getArea());
        userAddressExpDto.setStreet(sysBizUserAddress.getStreet());
        // 时间戳
        String timeStamp = String.valueOf(System.currentTimeMillis());

        // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
        String sign = null;
        try {
            sign = SignatureUtils.signWithSHA1(JSON.toJSONString(userAddressExpDto), SignatureUtils.getPrivateKey(privateKey));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("timeStamp", timeStamp);
        requestBody.put("sign", sign);
        requestBody.put("data", JSON.toJSONString(userAddressExpDto));
        log.info("请求体:{}", JSON.toJSONString(userAddressExpDto));

        // 发送 POST 请求
        String response = HttpUtil.postJson(merchantUrl, JSON.toJSONString(requestBody));
        log.info("订单推送------------:{}", response);
        // 解析响应
        JSONObject jsonResponse = JSON.parseObject(response);
        int code = jsonResponse.getIntValue("code");
        log.info("返回值------------:{}", jsonResponse);
    }
}
